/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mhv.fr.sprite.container;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import mhv.fr.sprite.Sprite;

/**
 *
 * @author Marc-Henri
 */
public class SpriteContainer {

    private HashMap<Long, Sprite> spriteMap;
    private long spriteCounter;
    private LinkedList<Long> spriteToDelete;
    private HashMap<Long, Sprite> spriteToAdd;

    /**
     * Create the instance of the sprite manager.
     */
    private static class SpriteContainerHolder {

        private final static SpriteContainer instance = new SpriteContainer();
    }

    /**
     * Return the instance of the sprite manager.
     * @return SpriteContainer
     */
    public static SpriteContainer getInstance() {
        return SpriteContainerHolder.instance;
    }

    public long add(Sprite sprite) {
        spriteCounter++;
        sprite.getController().setSpriteId(spriteCounter);
        spriteToAdd.put(new Long(spriteCounter), sprite);

        return spriteCounter;
    }

    public void delete(long ID) {
        spriteToDelete.add(ID);
        Sprite sp = spriteMap.get(ID);
        sp.setAlive(false);
    }

    public void applyChange() {
        for (Iterator<Long> it = spriteToDelete.iterator(); it.hasNext();) {
            Long ID = it.next();
            spriteMap.remove(ID);
        }
        spriteToDelete.clear();

        Set ListId = spriteToAdd.keySet();
        for (Iterator it = ListId.iterator(); it.hasNext();) {
            Object ID = it.next();
            spriteMap.put((Long)ID, spriteToAdd.get(ID));
        }
        spriteToAdd.clear();
    }

    public Sprite getSprite(long ID) {
        return spriteMap.get(ID);
    }

    public Collection<Sprite> getList() {
        return spriteMap.values();
    }

    public HashMap<Long, Sprite> getMap() {
        return spriteMap;
    }

    public void Clear() {
        spriteMap.clear();
        spriteToDelete.clear();
        spriteToAdd.clear();
        spriteCounter = 0;
    }

    private SpriteContainer() {
        spriteMap = new HashMap<Long, Sprite>();
        spriteToDelete = new LinkedList<Long>();
        spriteToAdd = new HashMap<Long, Sprite>();
        spriteCounter = 0;
    }
}
